package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"social-ecom/cache"
	"social-ecom/models"
	"social-ecom/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{

			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户名不存在",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
}
func Add(c *gin.Context) {

	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.List{

		Title:   title,
		Content: content,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "发布失败",
		})
		return
	}
	Reids_trl := "data_id_" + strconv.Itoa(int(data.ID))
	var newd models.List
	models.DB.Where("id=?", data.ID).First(&newd)
	jsondata, _ := json.Marshal(newd)
	cache.Rdb.Set(cache.Ctx, Reids_trl, jsondata, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var arr models.List
	err := models.DB.Where("id=?", id).First(&arr).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "详情失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情成功",
		"list": arr,
	})
}
func Del(c *gin.Context) {
	id := c.Query("id")
	var arr models.List
	models.DB.Where("id=?", id).Delete(&arr)
	Redis_trl := "trac_id" + id
	cache.Rdb.Del(cache.Ctx, Redis_trl)
	c.JSON(200, gin.H{
		"code": 400,
		"msg":  "删除成功",
	})
	return
}
func List(c *gin.Context) {
	var arr []models.List

	Redis_trl := "redis_trl"
	ListData, _ := cache.Rdb.Get(cache.Ctx, Redis_trl).Result()
	if ListData == "" {
		models.DB.Find(&arr)
		jsonData, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, Redis_trl, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(ListData), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})

}
